package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.enums.DownloadExcelTypeEnum;
import com.xbongbong.paas.help.PaasExcelExportHelp;
import com.xbongbong.paas.pojo.ExportStatusPojo;
import com.xbongbong.paas.pojo.dto.CoverFormDataDTO;
import com.xbongbong.paas.pojo.dto.ExcelExplainGetDTO;
import com.xbongbong.paas.pojo.dto.ExcelTemplateDTO;
import com.xbongbong.paas.pojo.dto.ImportFormDataDTO;
import com.xbongbong.paas.pojo.dto.NoSignFormDataDTO;
import com.xbongbong.paas.pojo.vo.ExcelTemplateVO;
import com.xbongbong.paas.pojo.vo.ExportCommunicateCountVO;
import com.xbongbong.paas.pojo.vo.ExportPartialExplainVO;
import com.xbongbong.paas.pojo.vo.ImportAttrsVO;
import com.xbongbong.paas.pojo.vo.ImportFormDataVO;
import com.xbongbong.paas.pojo.vo.ImportStatusVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.service.PaasExcelService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.webexport.dto.CommunicatePlanExportDTO;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.OutputStream;
import java.util.Objects;

/**
 * 导入导出相关接口
 *
 * @author wufeng
 * @date 2018/9/21 10:57
 */
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/file/excel")
public class PaasExcelController {

    @Resource
    private PaasExcelService paasExcelService;
    @Resource
    private PaasRedisHelper paasRedisHelper;

    /**
     * 导入模板下载
     */
    @RequestMapping(value = "/template/download")
    public String templateDownLoad(@RequestBody @Valid ExcelTemplateDTO excelTemplateDTO, BindingResult br, HttpServletResponse httpServletResponse) throws Exception {
        XbbResponse<ExcelTemplateVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            ExcelTemplateVO excelTemplateVO = new ExcelTemplateVO();
            try {
                TransmittableThreadLocalUtil.setValue(excelTemplateDTO.getSaasMark(), excelTemplateDTO.getBusinessType(), excelTemplateDTO.getMenuId(), excelTemplateDTO.getDistributorMark());
                excelTemplateVO = paasExcelService.templateDownLoad(excelTemplateDTO);
                httpServletResponse.reset();
                httpServletResponse.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(excelTemplateVO.getName(), "utf-8"));
                OutputStream toClient = httpServletResponse.getOutputStream();
                httpServletResponse.setContentType("application/vnd.ms-excel;charset=utf-8");
                excelTemplateVO.getWorkbook().write(toClient);
                toClient.flush();
                toClient.close();
                return null;
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            } finally {
                PaasExcelExportHelp.closeWorkBookException(excelTemplateVO.getWorkbook());
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 导入字段下载
     */
    @RequestMapping(value = "/import/getAttrs")
    public String templateGetAttrs(@RequestBody @Valid ExcelTemplateDTO excelTemplateDTO, BindingResult br) throws Exception {
        XbbResponse<ImportAttrsVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                UserVO userVo = paasExcelService.getUserVo(excelTemplateDTO.getCorpid(), excelTemplateDTO.getUserId());
                excelTemplateDTO.setLoginUser(userVo);
                excelTemplateDTO.setLoginUserName(userVo.getName());
                TransmittableThreadLocalUtil.setValue(excelTemplateDTO.getSaasMark(), excelTemplateDTO.getBusinessType(), excelTemplateDTO.getMenuId(), excelTemplateDTO.getDistributorMark());
                ImportAttrsVO importAttrsVO = paasExcelService.getAttrs(excelTemplateDTO);
                response = new XbbResponse<>(importAttrsVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.IgnoreNonFieldGetter);
    }


    /**
     * 导入数据
     */
    @RequestMapping(value = "/import/form/data")
    public String importFormData(@RequestBody @Valid ImportFormDataDTO importFormDataDTO, BindingResult br) throws Exception {
        XbbResponse<ImportFormDataVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                // 判断是否跳过重复提交校验
                if (!Boolean.TRUE.equals(importFormDataDTO.getIgnoreConCheck())) {
                    //重复提交校验
                    if (!paasRedisHelper.checkConcurrentLock(importFormDataDTO)) {
                        response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                        return JSON.toJSONString(response);
                    }
                }
                UserVO userVo = paasExcelService.getUserVo(importFormDataDTO.getCorpid(), importFormDataDTO.getUserId());
                importFormDataDTO.setLoginUser(userVo);
                importFormDataDTO.setLoginUserName(userVo.getName());
                ImportFormDataVO importFormDataVO = paasExcelService.importFormData(importFormDataDTO);
                response = new XbbResponse<>(importFormDataVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }


    /**
     * 导入覆盖数据
     */
    @RequestMapping(value = "/import/coverFormData")
    public String coverFormData(@RequestBody @Valid CoverFormDataDTO coverFormDataDTO, BindingResult br) {
        XbbResponse<ImportFormDataVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                // 判断是否跳过重复提交校验
                if (!Boolean.TRUE.equals(coverFormDataDTO.getIgnoreConCheck())) {
                    //重复提交校验
                    if (!paasRedisHelper.checkConcurrentLock(coverFormDataDTO)) {
                        response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                        return JSON.toJSONString(response);
                    }
                }
                ImportFormDataDTO importFormDataDTO = new ImportFormDataDTO();
                BeanUtil.copyProperties(coverFormDataDTO, importFormDataDTO);
                TransmittableThreadLocalUtil.setValue(importFormDataDTO.getSaasMark(), importFormDataDTO.getBusinessType(), importFormDataDTO.getMenuId(), coverFormDataDTO.getDistributorMark());
                ImportFormDataVO importFormDataVO = paasExcelService.coverFormData(importFormDataDTO);
                response = new XbbResponse<>(importFormDataVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 导入无签订人数据
     */
    @RequestMapping(value = "/import/noSignFormData")
    public String importNoSignFormData(@RequestBody @Valid NoSignFormDataDTO noSignFormDataDTO, BindingResult br) {
        XbbResponse<ImportFormDataVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                // 判断是否跳过重复提交校验
                if (!Boolean.TRUE.equals(noSignFormDataDTO.getIgnoreConCheck())) {
                    //重复提交校验
                    if (!paasRedisHelper.checkConcurrentLock(noSignFormDataDTO)) {
                        response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100003));
                        return JSON.toJSONString(response);
                    }
                }
                ImportFormDataDTO importFormDataDTO = new ImportFormDataDTO();
                BeanUtil.copyProperties(noSignFormDataDTO, importFormDataDTO);
                TransmittableThreadLocalUtil.setValue(importFormDataDTO.getSaasMark(), importFormDataDTO.getBusinessType(), importFormDataDTO.getMenuId(), importFormDataDTO.getDistributorMark());
                ImportFormDataVO importFormDataVO = paasExcelService.importNoSignFormData(importFormDataDTO);
                response = new XbbResponse<>(importFormDataVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 导入错误excel下载
     */
    @RequestMapping(value = "/error/download", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String errorDownload(@RequestBody @Valid ExcelTemplateDTO excelTemplateDTO, BindingResult br, HttpServletResponse httpServletResponse) {
        XbbResponse<ExcelTemplateVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            Workbook errorExcel = null;
            try {
                TransmittableThreadLocalUtil.setValue(excelTemplateDTO.getSaasMark(), excelTemplateDTO.getBusinessType(), excelTemplateDTO.getMenuId(), excelTemplateDTO.getDistributorMark());
                String name = I18nMessageUtil.getMessage(I18nStringConstant.ERROR_DATA_EXCEL);
                excelTemplateDTO.setExcelType(DownloadExcelTypeEnum.ERROR.getType());
                errorExcel = paasExcelService.errorOrUpdateDownLoad(excelTemplateDTO);
                // 清空response
                httpServletResponse.reset();
                // 设置response的Header
                httpServletResponse.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(name, "utf-8"));
                OutputStream toClient = httpServletResponse.getOutputStream();
                httpServletResponse.setContentType("application/vnd.ms-excel;charset=utf-8");
                errorExcel.write(toClient);
                toClient.flush();
                toClient.close();
                return null;
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            } finally {
                PaasExcelExportHelp.closeWorkBookException(errorExcel);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 导入覆盖数据excel下载
     */
    @RequestMapping(value = "/update/download", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateDownload(@RequestBody @Valid ExcelTemplateDTO excelTemplateDTO, BindingResult br, HttpServletResponse httpServletResponse) {
        XbbResponse<ExcelTemplateVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            Workbook errorExcel = null;
            try {
                TransmittableThreadLocalUtil.setValue(excelTemplateDTO.getSaasMark(), excelTemplateDTO.getBusinessType(), excelTemplateDTO.getMenuId(), excelTemplateDTO.getDistributorMark());
                String name = I18nMessageUtil.getMessage(I18nStringConstant.REPEAT_DATA_EXCEL);
                excelTemplateDTO.setExcelType(DownloadExcelTypeEnum.UPDATE.getType());
                errorExcel = paasExcelService.errorOrUpdateDownLoad(excelTemplateDTO);
                // 清空response
                httpServletResponse.reset();
                // 设置response的Header
                httpServletResponse.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(name, "utf-8"));
                OutputStream toClient = httpServletResponse.getOutputStream();
                httpServletResponse.setContentType("application/vnd.ms-excel;charset=utf-8");
                errorExcel.write(toClient);
                toClient.flush();
                toClient.close();
                return null;
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            } finally {
                PaasExcelExportHelp.closeWorkBookException(errorExcel);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 导入覆盖数据excel下载
     */
    @RequestMapping(value = "/noSign/download", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String noSignDownload(@RequestBody @Valid ExcelTemplateDTO excelTemplateDTO, BindingResult br, HttpServletResponse httpServletResponse) {
        XbbResponse<ExcelTemplateVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            Workbook errorExcel = null;
            try {
                TransmittableThreadLocalUtil.setValue(excelTemplateDTO.getSaasMark(), excelTemplateDTO.getBusinessType(), excelTemplateDTO.getMenuId(), excelTemplateDTO.getDistributorMark());
                String name = I18nMessageUtil.getMessage(I18nStringConstant.SIGN_ERROR_DATA_EXCEL);
                excelTemplateDTO.setExcelType(DownloadExcelTypeEnum.NO_SIGN.getType());
                errorExcel = paasExcelService.errorOrUpdateDownLoad(excelTemplateDTO);
                // 清空response
                httpServletResponse.reset();
                // 设置response的Header
                httpServletResponse.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(name, "utf-8"));
                OutputStream toClient = httpServletResponse.getOutputStream();
                httpServletResponse.setContentType("application/vnd.ms-excel;charset=utf-8");
                errorExcel.write(toClient);
                toClient.flush();
                toClient.close();
                return null;
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            } finally {
                PaasExcelExportHelp.closeWorkBookException(errorExcel);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 获取导入excel状态
     *
     * @param baseDTO 前端入参
     * @param br      校验结果
     * @return String
     */
    @RequestMapping(value = "/getImportStatus", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getImportStatus(@RequestBody @Valid BaseDTO baseDTO, BindingResult br) {
        XbbResponse<ImportStatusVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ImportStatusVO importStatusVO = paasExcelService.getImportStatus(baseDTO);
                response = new XbbResponse<>(importStatusVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 获取导出excel状态
     *
     * @param baseDTO 前端入参
     * @param br      校验结果
     * @return String
     */
    @RequestMapping(value = "/getExportStatus", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getExportStatus(@RequestBody @Valid BaseDTO baseDTO, BindingResult br) {
        XbbResponse<ExportStatusPojo> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ExportStatusPojo exportStatusPojo = paasExcelService.getExportStatus(baseDTO);
                response = new XbbResponse<>(exportStatusPojo);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 清除导入状态缓存
     *
     * @param baseDTO 前端入参
     * @param br      校验结果
     * @return String
     */
    @RequestMapping(value = "/delImportStatus", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String delImportStatus(@RequestBody @Valid BaseDTO baseDTO, BindingResult br) {
        XbbResponse<Boolean> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                boolean result = paasExcelService.delImportStatus(baseDTO);
                response = new XbbResponse<>(result);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 清除导出状态缓存
     *
     * @param baseDTO 前端入参
     * @param br      校验结果
     * @return String
     */
    @RequestMapping(value = "/delExportStatus", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String delExportStatus(@RequestBody @Valid BaseDTO baseDTO, BindingResult br) {
        XbbResponse<Boolean> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                boolean result = paasExcelService.delExportStatus(baseDTO);
                response = new XbbResponse<>(result);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            }
        }
        return JSON.toJSONString(response);
    }
    /**
     * 自定义导出获取解释
     */
    @RequestMapping(value = "/getExplainList", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getExplainList(@RequestBody @Valid ExcelExplainGetDTO excelExplainGetDTO, BindingResult br) {
        XbbResponse<ExportPartialExplainVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ExportPartialExplainVO result = paasExcelService.getExplainList(excelExplainGetDTO);
                response = new XbbResponse<>(result);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            }
        }
        return JSON.toJSONString(response);
    }
    /**
     * 访客计划导出，根据条件筛选，获取总数
     */
    @RequestMapping(value = "/getExportCommunicatePlanCount")
    public String getExportCommunicatePlanCount(@RequestBody @Valid CommunicatePlanExportDTO communicatePlanExportDTO, BindingResult br, HttpServletRequest request, HttpServletResponse httpServletResponse) throws Exception {
        XbbResponse<ExportCommunicateCountVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TransmittableThreadLocalUtil.setValue(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.COMMUNICATE_PLAN.getCode(), null, communicatePlanExportDTO.getDistributorMark());
                ExportCommunicateCountVO exportCommunicateCountVO = paasExcelService.getExportCommunicatePlanCount(communicatePlanExportDTO);
                response = new XbbResponse<>(exportCommunicateCountVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            }
        }
        return JSON.toJSONString(response, SerializerFeature.IgnoreNonFieldGetter);
    }


}
